package com.jzo2o.knife4j.config;

import com.jzo2o.common.model.Result;
import com.jzo2o.knife4j.filter.SwaggerFilter;
import com.jzo2o.knife4j.properties.SwaggerProperties;
import com.fasterxml.classmate.TypeResolver;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Resource;

/**
 * Knife4j(Swagger)配置类，用于初始化Swagger文档生成相关配置
 */
@Configuration
@EnableConfigurationProperties({SwaggerProperties.class}) // 启用Swagger配置属性绑定
@Import(SwaggerFilter.class) // 导入Swagger响应转换过滤器
@ConditionalOnProperty(prefix = "swagger", name = "enable", havingValue = "true") // 仅当swagger.enable=true时生效
public class Knife4jConfiguration {

    @Resource
    private SwaggerProperties swaggerProperties;

    /**
     * 构建Swagger核心配置对象Docket，定义文档生成规则
     * @param typeResolver 类型解析器，用于处理通用响应类型Result
     * @return Swagger配置对象Docket
     */
    @Bean(value = "defaultApi2")
    public Docket defaultApi2(TypeResolver typeResolver) {
        // 1.初始化Docket（指定Swagger文档版本为2.0）
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        // 2.添加通用响应类型Result到Swagger模型中
        docket.additionalModels(typeResolver.resolve(Result.class));

        // 3.配置Swagger文档基本信息及接口扫描规则
        return docket.apiInfo(new ApiInfoBuilder()
                        // 文档标题
                        .title(this.swaggerProperties.getTitle())
                        // 文档描述
                        .description(this.swaggerProperties.getDescription())
                        // 联系人信息
                        .contact(new Contact(
                                this.swaggerProperties.getContactName(),
                                this.swaggerProperties.getContactUrl(),
                                this.swaggerProperties.getContactEmail()))
                        // 应用版本
                        .version(this.swaggerProperties.getVersion())
                        .build())
                // 选择需要生成文档的接口
                .select()
                // 指定扫描的Controller包路径
                .apis(RequestHandlerSelectors.basePackage(this.swaggerProperties.getPackagePath()))
                // 匹配所有路径（所有接口都生成文档）
                .paths(PathSelectors.any())
                .build();
    }
}
